package com.yunke.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunke.common.exception.YunkeException;
import com.yunke.dto.vip.YunkeVipBuyDto;
import com.yunke.entity.*;
import com.yunke.mapper.*;
import com.yunke.service.YunkeUserService;
import com.yunke.service.YunkeVipService;
import com.yunke.vo.vip.YunkeVipLevelVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * VIP会员Service实现类
 * 
 * @author yunke
 * @since 1.0.0
 */
@Slf4j
@Service
public class YunkeVipServiceImpl extends ServiceImpl<YunkeLevelMapper, YunkeLevel> implements YunkeVipService {

    @Autowired
    private YunkeLevelMapper levelMapper;

    @Autowired
    private YunkeLevelOrderMapper levelOrderMapper;

    @Autowired
    private YunkeLevelCamiMapper levelCamiMapper;

    @Autowired
    private YunkeUserService userService;

    @Override
    public List<YunkeVipLevelVo> getVipLevelList() {
        log.info("获取VIP等级列表");
        
        try {
            // 查询可用的VIP等级
            LambdaQueryWrapper<YunkeLevel> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(YunkeLevel::getStatus, 1)
                    .orderByAsc(YunkeLevel::getLevelRank);
            
            List<YunkeLevel> levelList = this.list(wrapper);
            
            // 转换为VO
            List<YunkeVipLevelVo> result = levelList.stream()
                    .map(this::convertToLevelVo)
                    .collect(Collectors.toList());
            
            log.info("获取VIP等级列表成功，数量：{}", result.size());
            return result;
        } catch (Exception e) {
            log.error("获取VIP等级列表失败", e);
            throw new YunkeException("获取VIP等级列表失败");
        }
    }

    @Override
    public YunkeVipLevelVo getVipLevelDetail(Long levelId) {
        log.info("获取VIP等级详情，等级ID：{}", levelId);
        
        try {
            YunkeLevel level = this.getById(levelId);
            if (level == null || level.getStatus() != 1) {
                throw new YunkeException("VIP等级不存在或已下架");
            }
            
            YunkeVipLevelVo result = convertToLevelVo(level);
            
            log.info("获取VIP等级详情成功，等级：{}", level.getLevelName());
            return result;
        } catch (Exception e) {
            log.error("获取VIP等级详情失败，等级ID：{}", levelId, e);
            throw new YunkeException("获取VIP等级详情失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> buyVip(YunkeVipBuyDto vipBuyDto) {
        // 检查登录状态
        if (!StpUtil.isLogin()) {
            throw new YunkeException("请先登录");
        }

        Long currentUserId = StpUtil.getLoginIdAsLong();
        log.info("购买VIP，用户ID：{}，等级ID：{}", currentUserId, vipBuyDto.getLevelId());

        try {
            // 验证VIP等级
            YunkeLevel level = this.getById(vipBuyDto.getLevelId());
            if (level == null || level.getStatus() != 1) {
                throw new YunkeException("VIP等级不存在或已下架");
            }

            // 计算价格
            BigDecimal price = calculatePrice(level, vipBuyDto.getBuyType());
            
            // 创建订单
            YunkeLevelOrder order = createVipOrder(currentUserId, level, vipBuyDto, price);
            
            // 处理支付
            Map<String, Object> payResult = processPayment(order, vipBuyDto.getPayMethod());
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("orderNo", order.getOrderNo());
            result.put("payAmount", order.getPayAmount());
            result.put("payResult", payResult);
            
            log.info("购买VIP成功，订单号：{}", order.getOrderNo());
            return result;
        } catch (Exception e) {
            log.error("购买VIP失败，用户ID：{}", currentUserId, e);
            throw new YunkeException("购买VIP失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> createVipOrder(YunkeVipBuyDto vipBuyDto) {
        // 检查登录状态
        if (!StpUtil.isLogin()) {
            throw new YunkeException("请先登录");
        }

        Long currentUserId = StpUtil.getLoginIdAsLong();
        log.info("创建VIP订单，用户ID：{}，等级ID：{}", currentUserId, vipBuyDto.getLevelId());

        try {
            // 验证VIP等级
            YunkeLevel level = this.getById(vipBuyDto.getLevelId());
            if (level == null || level.getStatus() != 1) {
                throw new YunkeException("VIP等级不存在或已下架");
            }

            // 计算价格
            BigDecimal price = calculatePrice(level, vipBuyDto.getBuyType());
            
            // 创建订单
            YunkeLevelOrder order = createVipOrder(currentUserId, level, vipBuyDto, price);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("orderNo", order.getOrderNo());
            result.put("levelName", order.getLevelName());
            result.put("buyType", order.getBuyType());
            result.put("buyTypeText", getBuyTypeText(order.getBuyType()));
            result.put("duration", order.getDuration());
            result.put("originalPrice", order.getOriginalPrice());
            result.put("payAmount", order.getPayAmount());
            result.put("discountAmount", order.getDiscountAmount());
            result.put("createTime", order.getCreateTime());
            
            log.info("创建VIP订单成功，订单号：{}", order.getOrderNo());
            return result;
        } catch (Exception e) {
            log.error("创建VIP订单失败，用户ID：{}", currentUserId, e);
            throw new YunkeException("创建VIP订单失败：" + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getVipOrderStatus(String orderNo) {
        log.info("查询VIP订单状态，订单号：{}", orderNo);
        
        try {
            LambdaQueryWrapper<YunkeLevelOrder> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(YunkeLevelOrder::getOrderNo, orderNo);
            
            YunkeLevelOrder order = levelOrderMapper.selectOne(wrapper);
            if (order == null) {
                throw new YunkeException("订单不存在");
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("orderNo", order.getOrderNo());
            result.put("payStatus", order.getPayStatus());
            result.put("payStatusText", getPayStatusText(order.getPayStatus()));
            result.put("payAmount", order.getPayAmount());
            result.put("payTime", order.getPayTime());
            result.put("levelName", order.getLevelName());
            result.put("duration", order.getDuration());
            result.put("startTime", order.getStartTime());
            result.put("endTime", order.getEndTime());
            
            return result;
        } catch (Exception e) {
            log.error("查询VIP订单状态失败，订单号：{}", orderNo, e);
            throw new YunkeException("查询订单状态失败：" + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getMyVipInfo() {
        // 检查登录状态
        if (!StpUtil.isLogin()) {
            throw new YunkeException("请先登录");
        }

        Long currentUserId = StpUtil.getLoginIdAsLong();
        log.info("获取我的VIP信息，用户ID：{}", currentUserId);

        try {
            // 获取用户信息
            YunkeUser user = userService.getById(currentUserId);
            if (user == null) {
                throw new YunkeException("用户不存在");
            }

            // 查询当前有效的VIP订单
            LambdaQueryWrapper<YunkeLevelOrder> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(YunkeLevelOrder::getUserId, currentUserId)
                    .eq(YunkeLevelOrder::getPayStatus, 2) // 已支付
                    .gt(YunkeLevelOrder::getEndTime, System.currentTimeMillis())
                    .orderByDesc(YunkeLevelOrder::getEndTime)
                    .last("LIMIT 1");
            
            YunkeLevelOrder activeOrder = levelOrderMapper.selectOne(wrapper);
            
            Map<String, Object> result = new HashMap<>();
            
            if (activeOrder != null) {
                // 有活跃的VIP
                result.put("isVip", true);
                result.put("levelId", activeOrder.getLevelId());
                result.put("levelName", activeOrder.getLevelName());
                result.put("startTime", activeOrder.getStartTime());
                result.put("endTime", activeOrder.getEndTime());
                result.put("remainDays", calculateRemainDays(activeOrder.getEndTime()));
                result.put("isAutoRenew", activeOrder.getIsAutoRenew() == 1);
                
                // 获取VIP等级详情
                YunkeLevel level = this.getById(activeOrder.getLevelId());
                if (level != null) {
                    result.put("levelIcon", level.getLevelIcon());
                    result.put("levelColor", level.getLevelColor());
                    result.put("exclusiveTag", level.getExclusiveTag());
                    
                    // 解析权益
                    if (StrUtil.isNotBlank(level.getPrivileges())) {
                        List<YunkeVipLevelVo.VipPrivilege> privileges = 
                                JSONUtil.toList(level.getPrivileges(), YunkeVipLevelVo.VipPrivilege.class);
                        result.put("privileges", privileges);
                    }
                }
            } else {
                // 非VIP用户
                result.put("isVip", false);
                result.put("levelName", "普通用户");
                result.put("remainDays", 0);
                result.put("privileges", new ArrayList<>());
            }
            
            // 统计信息
            result.put("totalSpent", getTotalSpent(currentUserId));
            result.put("orderCount", getOrderCount(currentUserId));
            
            log.info("获取我的VIP信息成功，用户ID：{}，是否VIP：{}", currentUserId, result.get("isVip"));
            return result;
        } catch (Exception e) {
            log.error("获取我的VIP信息失败，用户ID：{}", currentUserId, e);
            throw new YunkeException("获取VIP信息失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> exchangeVipCard(String camiCode) {
        // 检查登录状态
        if (!StpUtil.isLogin()) {
            throw new YunkeException("请先登录");
        }

        Long currentUserId = StpUtil.getLoginIdAsLong();
        log.info("卡密兑换VIP，用户ID：{}，卡密：{}", currentUserId, camiCode);

        try {
            // 查询卡密
            LambdaQueryWrapper<YunkeLevelCami> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(YunkeLevelCami::getCamiCode, camiCode)
                    .eq(YunkeLevelCami::getStatus, 1);
            
            YunkeLevelCami cami = levelCamiMapper.selectOne(wrapper);
            if (cami == null) {
                throw new YunkeException("卡密不存在或已失效");
            }
            
            if (cami.getUseStatus() == 1) {
                throw new YunkeException("卡密已被使用");
            }
            
            if (cami.getUseStatus() == 2) {
                throw new YunkeException("卡密已过期");
            }
            
            // 检查有效期
            long currentTime = System.currentTimeMillis();
            if (cami.getValidEndTime() != null && currentTime > cami.getValidEndTime()) {
                // 更新卡密状态为已过期
                cami.setUseStatus(2);
                cami.setUpdateTime(currentTime);
                levelCamiMapper.updateById(cami);
                throw new YunkeException("卡密已过期");
            }
            
            // 使用卡密
            cami.setUseUserId(currentUserId);
            cami.setUseTime(currentTime);
            cami.setUseStatus(1);
            cami.setUpdateTime(currentTime);
            levelCamiMapper.updateById(cami);
            
            // 创建VIP订单
            YunkeLevelOrder order = createVipOrderFromCami(currentUserId, cami);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "卡密兑换成功");
            result.put("orderNo", order.getOrderNo());
            result.put("levelName", order.getLevelName());
            result.put("duration", order.getDuration());
            result.put("startTime", order.getStartTime());
            result.put("endTime", order.getEndTime());
            
            log.info("卡密兑换VIP成功，用户ID：{}，订单号：{}", currentUserId, order.getOrderNo());
            return result;
        } catch (Exception e) {
            log.error("卡密兑换VIP失败，用户ID：{}，卡密：{}", currentUserId, camiCode, e);
            throw new YunkeException("卡密兑换失败：" + e.getMessage());
        }
    }

    @Override
    public Page<Map<String, Object>> getVipOrderList(Long current, Long size) {
        // 检查登录状态
        if (!StpUtil.isLogin()) {
            throw new YunkeException("请先登录");
        }

        Long currentUserId = StpUtil.getLoginIdAsLong();
        log.info("获取VIP购买记录，用户ID：{}", currentUserId);

        try {
            Page<YunkeLevelOrder> page = new Page<>(current, size);
            LambdaQueryWrapper<YunkeLevelOrder> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(YunkeLevelOrder::getUserId, currentUserId)
                    .orderByDesc(YunkeLevelOrder::getCreateTime);
            
            Page<YunkeLevelOrder> orderPage = levelOrderMapper.selectPage(page, wrapper);
            
            Page<Map<String, Object>> result = new Page<>();
            result.setCurrent(orderPage.getCurrent());
            result.setSize(orderPage.getSize());
            result.setTotal(orderPage.getTotal());
            
            List<Map<String, Object>> records = orderPage.getRecords().stream()
                    .map(this::convertToOrderVo)
                    .collect(Collectors.toList());
            result.setRecords(records);
            
            log.info("获取VIP购买记录成功，用户ID：{}，数量：{}", currentUserId, records.size());
            return result;
        } catch (Exception e) {
            log.error("获取VIP购买记录失败，用户ID：{}", currentUserId, e);
            throw new YunkeException("获取购买记录失败：" + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> checkVipRights(String privilege) {
        // 检查登录状态
        if (!StpUtil.isLogin()) {
            throw new YunkeException("请先登录");
        }

        Long currentUserId = StpUtil.getLoginIdAsLong();
        log.info("检查VIP权益，用户ID：{}，权益：{}", currentUserId, privilege);

        try {
            Map<String, Object> vipInfo = getMyVipInfo();
            boolean isVip = (Boolean) vipInfo.get("isVip");
            
            Map<String, Object> result = new HashMap<>();
            result.put("hasRight", false);
            result.put("isVip", isVip);
            result.put("privilege", privilege);
            
            if (isVip) {
                // 检查具体权益
                @SuppressWarnings("unchecked")
                List<YunkeVipLevelVo.VipPrivilege> privileges = 
                        (List<YunkeVipLevelVo.VipPrivilege>) vipInfo.get("privileges");
                
                if (privileges != null) {
                    boolean hasRight = privileges.stream()
                            .anyMatch(p -> privilege.equals(p.getName()) && p.getEnabled());
                    result.put("hasRight", hasRight);
                }
                
                result.put("levelName", vipInfo.get("levelName"));
                result.put("endTime", vipInfo.get("endTime"));
                result.put("remainDays", vipInfo.get("remainDays"));
            }
            
            return result;
        } catch (Exception e) {
            log.error("检查VIP权益失败，用户ID：{}，权益：{}", currentUserId, privilege, e);
            throw new YunkeException("检查权益失败：" + e.getMessage());
        }
    }

    // TODO: 管理员功能，暂时返回占位数据
    @Override
    public Map<String, Object> generateVipCard(Long levelId, Integer count, Integer validDays) {
        log.info("生成VIP卡密，等级ID：{}，数量：{}，有效天数：{}", levelId, count, validDays);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", "管理员功能开发中");
        return result;
    }

    @Override
    public Map<String, Object> getVipStatistics() {
        log.info("获取VIP统计信息");
        
        Map<String, Object> result = new HashMap<>();
        result.put("totalVipUsers", 0);
        result.put("activeVipUsers", 0);
        result.put("totalRevenue", BigDecimal.ZERO);
        result.put("monthlyRevenue", BigDecimal.ZERO);
        return result;
    }

    @Override
    public Map<String, Object> renewVip(YunkeVipBuyDto renewDto) {
        log.info("VIP续费");
        // 续费逻辑与购买类似，暂时调用购买方法
        return buyVip(renewDto);
    }

    @Override
    public Map<String, Object> refundVip(String orderNo, String reason) {
        log.info("VIP退款申请，订单号：{}，原因：{}", orderNo, reason);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", "退款功能开发中");
        return result;
    }

    /**
     * 转换为等级VO
     */
    private YunkeVipLevelVo convertToLevelVo(YunkeLevel level) {
        YunkeVipLevelVo vo = new YunkeVipLevelVo();
        BeanUtils.copyProperties(level, vo);
        vo.setLevelId(level.getId());
        vo.setIsRecommend(level.getIsRecommend() == 1);
        vo.setIsLimited(level.getIsLimited() == 1);
        vo.setStatusText(getLevelStatusText(level.getStatus()));
        
        // 计算最优惠价格
        BigDecimal bestPrice = Collections.min(Arrays.asList(
                level.getMonthPrice(), level.getQuarterPrice(), level.getYearPrice()));
        vo.setBestPrice(bestPrice);
        
        if (bestPrice.equals(level.getYearPrice())) {
            vo.setBestPriceType("年费");
            vo.setSavedAmount(level.getMonthPrice().multiply(BigDecimal.valueOf(12)).subtract(level.getYearPrice()));
        } else if (bestPrice.equals(level.getQuarterPrice())) {
            vo.setBestPriceType("季费");
            vo.setSavedAmount(level.getMonthPrice().multiply(BigDecimal.valueOf(3)).subtract(level.getQuarterPrice()));
        } else {
            vo.setBestPriceType("月费");
            vo.setSavedAmount(BigDecimal.ZERO);
        }
        
        // 解析权益
        if (StrUtil.isNotBlank(level.getPrivileges())) {
            try {
                List<YunkeVipLevelVo.VipPrivilege> privileges = 
                        JSONUtil.toList(level.getPrivileges(), YunkeVipLevelVo.VipPrivilege.class);
                vo.setPrivileges(privileges);
            } catch (Exception e) {
                log.warn("解析VIP权益失败，等级ID：{}", level.getId(), e);
                vo.setPrivileges(new ArrayList<>());
            }
        } else {
            vo.setPrivileges(new ArrayList<>());
        }
        
        // 限时信息
        if (level.getIsLimited() == 1) {
            vo.setLimitInfo(formatLimitInfo(level.getLimitStartTime(), level.getLimitEndTime()));
        }
        
        return vo;
    }

    /**
     * 转换为订单VO
     */
    private Map<String, Object> convertToOrderVo(YunkeLevelOrder order) {
        Map<String, Object> vo = new HashMap<>();
        vo.put("orderNo", order.getOrderNo());
        vo.put("levelName", order.getLevelName());
        vo.put("buyType", order.getBuyType());
        vo.put("buyTypeText", getBuyTypeText(order.getBuyType()));
        vo.put("duration", order.getDuration());
        vo.put("originalPrice", order.getOriginalPrice());
        vo.put("payAmount", order.getPayAmount());
        vo.put("discountAmount", order.getDiscountAmount());
        vo.put("payMethod", order.getPayMethod());
        vo.put("payMethodText", getPayMethodText(order.getPayMethod()));
        vo.put("payStatus", order.getPayStatus());
        vo.put("payStatusText", getPayStatusText(order.getPayStatus()));
        vo.put("orderSource", order.getOrderSource());
        vo.put("orderSourceText", getOrderSourceText(order.getOrderSource()));
        vo.put("startTime", order.getStartTime());
        vo.put("endTime", order.getEndTime());
        vo.put("payTime", order.getPayTime());
        vo.put("createTime", order.getCreateTime());
        vo.put("isAutoRenew", order.getIsAutoRenew() == 1);
        return vo;
    }

    /**
     * 计算价格
     */
    private BigDecimal calculatePrice(YunkeLevel level, Integer buyType) {
        switch (buyType) {
            case 1: return level.getMonthPrice();
            case 2: return level.getQuarterPrice();
            case 3: return level.getYearPrice();
            default: throw new YunkeException("购买类型错误");
        }
    }

    /**
     * 创建VIP订单
     */
    private YunkeLevelOrder createVipOrder(Long userId, YunkeLevel level, YunkeVipBuyDto dto, BigDecimal price) {
        YunkeLevelOrder order = new YunkeLevelOrder();
        order.setOrderNo("VIP" + IdUtil.fastSimpleUUID());
        order.setUserId(userId);
        order.setLevelId(level.getId());
        order.setLevelName(level.getLevelName());
        order.setBuyType(dto.getBuyType());
        order.setDuration(calculateDuration(dto.getBuyType()));
        order.setOriginalPrice(price);
        order.setPayAmount(price); // TODO: 应用优惠券折扣
        order.setDiscountAmount(BigDecimal.ZERO);
        order.setPayMethod(dto.getPayMethod());
        order.setPayStatus(1); // 待支付
        order.setIsAutoRenew(dto.getIsAutoRenew() != null ? dto.getIsAutoRenew() : 0);
        order.setOrderSource(1); // 用户购买
        order.setRemark(dto.getRemark());
        
        long currentTime = System.currentTimeMillis();
        order.setCreateTime(currentTime);
        order.setUpdateTime(currentTime);
        
        levelOrderMapper.insert(order);
        return order;
    }

    /**
     * 从卡密创建VIP订单
     */
    private YunkeLevelOrder createVipOrderFromCami(Long userId, YunkeLevelCami cami) {
        YunkeLevelOrder order = new YunkeLevelOrder();
        order.setOrderNo("CAMI" + IdUtil.fastSimpleUUID());
        order.setUserId(userId);
        order.setLevelId(cami.getLevelId());
        order.setLevelName(cami.getLevelName());
        order.setBuyType(cami.getCamiType());
        order.setDuration(cami.getDuration());
        order.setOriginalPrice(cami.getCamiValue());
        order.setPayAmount(BigDecimal.ZERO); // 卡密兑换无需支付
        order.setDiscountAmount(cami.getCamiValue());
        order.setPayMethod(1); // 余额支付
        order.setPayStatus(2); // 已支付
        order.setOrderSource(4); // 卡密兑换
        
        long currentTime = System.currentTimeMillis();
        order.setStartTime(currentTime);
        order.setEndTime(currentTime + cami.getDuration() * 30L * 24L * 60L * 60L * 1000L); // 按月计算
        order.setActiveTime(currentTime);
        order.setPayTime(currentTime);
        order.setCreateTime(currentTime);
        order.setUpdateTime(currentTime);
        
        levelOrderMapper.insert(order);
        return order;
    }

    /**
     * 处理支付
     */
    private Map<String, Object> processPayment(YunkeLevelOrder order, Integer payMethod) {
        Map<String, Object> result = new HashMap<>();
        
        switch (payMethod) {
            case 1: // 余额支付
                result = processBalancePay(order);
                break;
            case 2: // 微信支付
                result = processWechatPay(order);
                break;
            case 3: // 支付宝支付
                result = processAliPay(order);
                break;
            default:
                throw new YunkeException("不支持的支付方式");
        }
        
        return result;
    }

    /**
     * 余额支付处理
     */
    private Map<String, Object> processBalancePay(YunkeLevelOrder order) {
        // TODO: 实现余额支付逻辑
        Map<String, Object> result = new HashMap<>();
        result.put("payType", "balance");
        result.put("message", "余额支付功能开发中");
        return result;
    }

    /**
     * 微信支付处理
     */
    private Map<String, Object> processWechatPay(YunkeLevelOrder order) {
        // TODO: 实现微信支付逻辑
        Map<String, Object> result = new HashMap<>();
        result.put("payType", "wechat");
        result.put("message", "微信支付功能开发中");
        return result;
    }

    /**
     * 支付宝支付处理
     */
    private Map<String, Object> processAliPay(YunkeLevelOrder order) {
        // TODO: 实现支付宝支付逻辑
        Map<String, Object> result = new HashMap<>();
        result.put("payType", "alipay");
        result.put("message", "支付宝支付功能开发中");
        return result;
    }

    /**
     * 计算时长（月）
     */
    private Integer calculateDuration(Integer buyType) {
        switch (buyType) {
            case 1: return 1;  // 月费
            case 2: return 3;  // 季费
            case 3: return 12; // 年费
            default: return 1;
        }
    }

    /**
     * 计算剩余天数
     */
    private Integer calculateRemainDays(Long endTime) {
        if (endTime == null) {
            return 0;
        }
        long remainMillis = endTime - System.currentTimeMillis();
        return Math.max(0, (int) (remainMillis / (24 * 60 * 60 * 1000)));
    }

    /**
     * 获取总消费
     */
    private BigDecimal getTotalSpent(Long userId) {
        LambdaQueryWrapper<YunkeLevelOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YunkeLevelOrder::getUserId, userId)
                .eq(YunkeLevelOrder::getPayStatus, 2); // 已支付
        
        List<YunkeLevelOrder> orders = levelOrderMapper.selectList(wrapper);
        return orders.stream()
                .map(YunkeLevelOrder::getPayAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    /**
     * 获取订单数量
     */
    private Integer getOrderCount(Long userId) {
        LambdaQueryWrapper<YunkeLevelOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YunkeLevelOrder::getUserId, userId);
        return Math.toIntExact(levelOrderMapper.selectCount(wrapper));
    }

    // 文本转换方法
    private String getLevelStatusText(Integer status) {
        switch (status) {
            case 1: return "正常";
            case 2: return "停售";
            case 3: return "下架";
            default: return "未知";
        }
    }

    private String getBuyTypeText(Integer buyType) {
        switch (buyType) {
            case 1: return "月费";
            case 2: return "季费";
            case 3: return "年费";
            default: return "未知";
        }
    }

    private String getPayStatusText(Integer payStatus) {
        switch (payStatus) {
            case 1: return "待支付";
            case 2: return "已支付";
            case 3: return "已取消";
            case 4: return "已退款";
            default: return "未知";
        }
    }

    private String getPayMethodText(Integer payMethod) {
        switch (payMethod) {
            case 1: return "余额支付";
            case 2: return "微信支付";
            case 3: return "支付宝支付";
            default: return "未知";
        }
    }

    private String getOrderSourceText(Integer orderSource) {
        switch (orderSource) {
            case 1: return "用户购买";
            case 2: return "系统赠送";
            case 3: return "活动奖励";
            case 4: return "卡密兑换";
            default: return "未知";
        }
    }

    private String formatLimitInfo(Long startTime, Long endTime) {
        if (startTime == null || endTime == null) {
            return "";
        }
        // TODO: 格式化限时信息
        return "限时活动进行中";
    }
}